//! MySQL集成测试
//! 使用配置文件中的设置进行数据库测试

use dataforge::db::DatabaseForge;
use dataforge::generators::name;
use dataforge::generators::internet;
use dataforge::generators::number;
use dataforge::generators::datetime;
use std::sync::Once;

// 引入配置模块
use crate::config::TestConfiguration;

static INIT: Once = Once::new();

/// 初始化测试环境
fn init_test_env() -> TestConfiguration {
    INIT.call_once(|| {
        // 可以在这里添加全局初始化逻辑
    });
    
    // 加载测试配置
    TestConfiguration::load_default().expect("Failed to load test configuration")
}

/// 测试MySQL连接
#[test]
#[ignore] // 默认忽略，只有在配置启用时才运行
fn test_mysql_connection() {
    let config = init_test_env();
    
    // 检查是否启用数据库测试
    if !config.is_database_test_enabled() {
        println!("Database tests are disabled. Set database.enabled = true in test_config.toml to enable.");
        return;
    }
    
    // 创建数据库填充器
    let forge = DatabaseForge::new(config.mysql_connection_string());
    
    // 测试连接（这里只是示例，实际实现可能需要根据DatabaseForge的API调整）
    println!("Testing MySQL connection with: {}", config.mysql_connection_string());
    
    // 如果需要实际测试连接，可以在这里添加连接测试逻辑
    // 例如：assert!(forge.test_connection().is_ok());
}

/// 测试MySQL数据填充
#[test]
#[ignore] // 默认忽略，只有在配置启用时才运行
fn test_mysql_data_filling() {
    let config = init_test_env();
    
    // 检查是否启用数据库测试
    if !config.is_database_test_enabled() {
        println!("Database tests are disabled. Set database.enabled = true in test_config.toml to enable.");
        return;
    }
    
    // 创建数据库填充器
    let forge = DatabaseForge::new(config.mysql_connection_string());
    
    // 配置表并填充数据
    let result = forge
        .table("users", config.sample_count(), |t| {
            t.field("id", || serde_json::json!(dataforge::uuid_v4()))
             .field("name", || serde_json::json!(name::zh_cn_fullname()))
             .field("email", || serde_json::json!(internet::email()))
             .field("phone", || serde_json::json!(number::phone_number_cn()))
             .field("created_at", || serde_json::json!(datetime::iso8601()))
        })
        .fill_sync();
    
    match result {
        Ok(count) => {
            println!("Successfully filled {} records", count);
            assert_eq!(count, config.sample_count());
        }
        Err(e) => {
            eprintln!("Failed to fill data: {}", e);
            // 在CI环境中可能需要跳过而不是失败
            panic!("Database filling failed: {}", e);
        }
    }
}

/// 测试MySQL批量插入性能
#[test]
#[ignore] // 默认忽略，只有在配置启用时才运行
fn test_mysql_batch_performance() {
    let config = init_test_env();
    
    // 检查是否启用数据库测试和性能测试
    if !config.is_database_test_enabled() {
        println!("Database tests are disabled. Set database.enabled = true in test_config.toml to enable.");
        return;
    }
    
    if !config.is_performance_test_enabled() {
        println!("Performance tests are disabled. Set test.performance.enabled = true in test_config.toml to enable.");
        return;
    }
    
    use std::time::Instant;
    
    // 创建数据库填充器
    let forge = DatabaseForge::new(config.mysql_connection_string())
        .batch_size(config.batch_size());
    
    let start = Instant::now();
    
    // 执行批量插入
    let result = forge
        .table("performance_test", config.performance_iterations(), |t| {
            t.field("id", || serde_json::json!(dataforge::uuid_v4()))
             .field("name", || serde_json::json!(name::zh_cn_fullname()))
             .field("email", || serde_json::json!(internet::email()))
             .field("score", || serde_json::json!(number::random_int(0, 100)))
             .field("created_at", || serde_json::json!(datetime::iso8601()))
        })
        .fill_sync();
    
    let duration = start.elapsed();
    
    match result {
        Ok(count) => {
            println!("Filled {} records in {:?}", count, duration);
            println!("Rate: {:.2} records/second", count as f64 / duration.as_secs_f64());
            assert_eq!(count, config.performance_iterations());
        }
        Err(e) => {
            eprintln!("Performance test failed: {}", e);
            panic!("Database performance test failed: {}", e);
        }
    }
}

/// 测试MySQL表结构推断
#[test]
#[ignore] // 默认忽略，只有在配置启用时才运行
fn test_mysql_schema_inference() {
    let config = init_test_env();
    
    // 检查是否启用数据库测试
    if !config.is_database_test_enabled() {
        println!("Database tests are disabled. Set database.enabled = true in test_config.toml to enable.");
        return;
    }
    
    // 创建数据库填充器
    let forge = DatabaseForge::new(config.mysql_connection_string());
    
    // 获取schema解析器
    let schema_parser = forge.schema_parser();
    
    // 这里可以添加schema推断的测试逻辑
    println!("Testing schema inference with MySQL");
    
    // 示例：推断一个简单的JSON结构
    let json_schema = serde_json::json!({
        "title": "User",
        "properties": {
            "id": {"type": "string", "format": "uuid"},
            "name": {"type": "string"},
            "age": {"type": "integer", "minimum": 0, "maximum": 150},
            "email": {"type": "string", "format": "email"}
        }
    });
    
    let result = schema_parser.infer_from_json(&json_schema);
    assert!(result.is_ok());
    
    let table_schema = result.unwrap();
    println!("Inferred table schema: {:?}", table_schema);
    
    // 验证推断的字段
    assert_eq!(table_schema.name, "User");
    assert_eq!(table_schema.fields.len(), 4);
    
    // 验证字段类型推断
    let id_field = table_schema.fields.iter().find(|f| f.name == "id").unwrap();
    let name_field = table_schema.fields.iter().find(|f| f.name == "name").unwrap();
    let age_field = table_schema.fields.iter().find(|f| f.name == "age").unwrap();
    let email_field = table_schema.fields.iter().find(|f| f.name == "email").unwrap();
    
    // 注意：实际的类型推断可能需要根据实现调整
    println!("ID field: {:?}", id_field);
    println!("Name field: {:?}", name_field);
    println!("Age field: {:?}", age_field);
    println!("Email field: {:?}", email_field);
}